package com.zhoutao123.hephaestus.service.impl;

import com.zhoutao123.hephaestus.object.bussiness.VBlogLook;
import com.zhoutao123.hephaestus.object.exception.NotFountException;
import com.zhoutao123.hephaestus.object.transport.BlogLookTO;
import com.zhoutao123.hephaestus.repository.entity.BlogLook;
import com.zhoutao123.hephaestus.repository.entity.BlogLookExample;
import com.zhoutao123.hephaestus.service.AbstractService;
import com.zhoutao123.hephaestus.service.BlogLookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class BlogLookServiceImpl extends AbstractService implements BlogLookService {

  @Override
  public VBlogLook add(String blogId, String userIp) {
    log.debug("调用增加文章访问量接口：id={},ip={}",blogId,userIp);
    BlogLookTO blogLookTO = new BlogLookTO();
    blogLookTO.setBlogId(blogId).setUserIp(userIp);
    BlogLook blogLook = blogLookTO.toEntity();
    blogLookMapper.insertSelective(blogLook);
    return getById(blogLook.getId());
  }

  @Override
  public List<VBlogLook> getByBlogId(String blogId) {
    BlogLookExample example = new BlogLookExample();
    example.createCriteria().andBlogIdEqualTo(blogId);
    List<BlogLook> blogLooks = blogLookMapper.selectByExample(example);
    return blogLooks.stream().map(VBlogLook::of).collect(Collectors.toList());
  }

  @Override
  public long getLookCountByBlogId(String blogId) {
    BlogLookExample example = new BlogLookExample();
    example.createCriteria().andBlogIdEqualTo(blogId);
    return blogLookMapper.countByExample(example);
  }

  @Override
  public VBlogLook getById(String blogLookId) {
    BlogLook blogLook = blogLookMapper.selectByPrimaryKey(blogLookId);
    if (blogLook == null) {
      throw new NotFountException("操作失败，浏览记录没有发现");
    }
    return VBlogLook.of(blogLook);
  }
}
